<?php


namespace app\api\controller;


use addons\shopro\library\Wechat;
use app\api\model\MeetModel;
use app\api\model\StoreOrderModel;
use app\api\model\StoreShopModel;
use app\common\controller\Api;
use think\Request;
use think\Session;

class Weixin extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['index','cate'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

/*
 * 小春科技企业号（企业微信）
 *         wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0
企业corpId:ww377c91a81493c595
agentId : 1000011
通讯录秘钥：wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0
会议秘钥：zTaBypRVRipVmyqdquF_KH7f1PFGmqpu1aSH3dAQ4E0
*/
// 企业号信息
    protected $corpId = 'ww377c91a81493c595';
    protected $agentId = '1000011';
    protected $secret = 'wrieS_MfpVjtlgrmKQWsEFdD7VS8CUgtnp4BrFXpXK0';
    protected $secret2 = 'zTaBypRVRipVmyqdquF_KH7f1PFGmqpu1aSH3dAQ4E0';


    public function randomkeys($length) {
        $returnStr='';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for($i = 0; $i < $length; $i ++) {
            $returnStr .= $pattern [mt_rand ( 0, 61 )];
        }
        return $returnStr;
    }

    /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
     public function send_post($url, $post_data, $type = 'GET') {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => $type,
                'header' => 'Content-type:text/json',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }



    public function makeSignature($args){
        return sha1($args);
    }



    public function token()
    {
        // 设置跨域请求头
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        $getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpId."&corpsecret=".$this->secret;
        $getTokenUrl2 = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpId."&corpsecret=".$this->secret2;

// 如果存在缓存文件，用缓存文件中的信息初始化签名数据
        $cacheData = array();
        if (Session::get('cacheData')) {
            $cacheData = Session::get('cacheData');
            // 判断缓存信息是否过期，如果过期删除缓存文件，并将data重置
            if (time() - $cacheData['timestamp']/1 >= 7200) {
                Session::clear('cacheData');
                $cacheData = array();
            }
        }
        // 如果缓存文件中已经存在token
        if (isset($cacheData['access_token'])) {
            $token = $cacheData['access_token'];
            $token2 = $cacheData['access_token2'];
            $onceStr = $cacheData['nonce_str'];
            $timeStamp = $cacheData['timestamp'];
        } else {
            $onceStr = $this->randomkeys(16);
            $timeStamp = time();
            // 请求微信接口获取access_token
            $data = json_decode($this->send_post($getTokenUrl, array()), true); //
            $data2 = json_decode($this->send_post($getTokenUrl2, array()), true);
            $token = $data['access_token'];
            $token2 = $data2['access_token'];
        }
// 缓存ticket和accessToken的配置信息
        $cacheData = array(
            'access_token' => $token,
            'access_token2' => $token2,
            'nonce_str' => $onceStr,
            'timestamp' => $timeStamp
        );
// 如果不存在缓存文件，则缓存， 否则不缓存
        if (!Session::has('cacheData')) {
            Session::set('cacheData', $cacheData);
        }
        return $cacheData;
    }



    public function get_wx_data()
    {
        Session::clear('cacheData');
        Session::set('cacheData',null);
        if (!Session::has('cacheData')) {
            $this->token();
        }
       // Session::set('departmentData',null);
        if (!Session::has('departmentData')) {
          $this->department();
        }
       // Session::set('userlistData',null);
        if (!Session::has('userlistData')) {
              $this->department_user();
        }
        $arr =["token"=>Session::get('cacheData'),'department'=>Session::get('departmentData')['list']['department'],'userlist'=>Session::get('userlistData')['list']['userlist']];

        $this->success("成功", $arr );
    }

    /*
     * 发送微信消息
     * */
    public function send()
    {
        $input =  input();
        print_r($input);
        $arrToken = $this->token();
        $access_token = $arrToken['access_token2'];
        $postUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$access_token;
        echo $postUrl;
        $data = json_decode($this->send_post($postUrl, $input,"POST"), true);
        $this->success("成功", $data);
    }


    public function department()
    {
        $arrToken = $this->token();
        $access_token = $arrToken['access_token'];
        $cacheData =[];
        if (Session::get('departmentData')) {
            $cacheData = Session::get('departmentData');
            // 判断缓存信息是否过期，如果过期删除缓存文件，并将data重置
            if (time() - $cacheData['timestamp']/1 >= 7200) {
                Session::clear('departmentData');
                $cacheData = array();
            }
        }
        // 如果缓存文件中已经存在token
        if (isset($cacheData['list'])) {
            $data = $cacheData['list'];
        } else {
            $getUrl = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$access_token;
            $data = json_decode($this->send_post($getUrl, array()), true);
        }

        if (!Session::has('departmentData')) {
            $cacheData = array(
                'list' => $data,
                'timestamp' =>  time()
            );
            Session::set('departmentData', $cacheData);
        }
        $this->success("成功", $data);
    }

    public function department_user()
    {
        $department_id = input('department_id') || 1;
        $arrToken = $this->token();
        $access_token = $arrToken['access_token'];
        $cacheData =[];
        if (Session::get('userlistData')) {
            $cacheData = Session::get('userlistData');
            // 判断缓存信息是否过期，如果过期删除缓存文件，并将data重置
            if (time() - $cacheData['timestamp']/1 >= 7200) {
                Session::clear('userlistData');
                $cacheData = array();
            }
        }
        // 如果缓存文件中已经存在token
        if (isset($cacheData['list'])) {
            $data = $cacheData['list'];
        } else {
            $getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=".$access_token."&fetch_child=1&department_id=".$department_id;
            $data = json_decode($this->send_post($getUrl, array()), true);
        }

        if (!Session::has('userlistData')) {
            $cacheData = array(
                'list' =>  $data,
                'timestamp' =>  time()
            );
            Session::set('userlistData', $cacheData);
        }
        $this->success("成功", $data['userlist']);
    }

    public function user_info()
    {
        $userid = input('userid');
        $arrToken = $this->token();
        $access_token = $arrToken['access_token'];
        $getUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$userid;
        $data = json_decode($this->send_post($getUrl, array()), true);
        $this->success("成功", $data );
    }



}
